package com.nc.user.service.impl;


import com.plug.BeanUtil;
import com.plug.result.RetResponse;
import com.plug.result.RetResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;


import com.nc.user.dao.FrmPermissionsDao;
import com.nc.user.dao.FrmRoleDao;
import com.nc.user.model.dto.RoleDto;
import com.nc.user.model.entity.FrmRole;
import com.nc.user.service.RoleService;

import javax.transaction.Transactional;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private FrmRoleDao roleDao;
    @Autowired
    private FrmPermissionsDao permissionsDao;

    @Transactional
    @Override
    public RetResult save(RoleDto roleDto) {
        try {
            FrmRole role = BeanUtil.convertToBean(roleDto, FrmRole.class);
            role.setPermissionsRole(permissionsDao.findByCodeIn(roleDto.getPermissionsCode()));
            roleDao.save(role);
            return RetResponse.makeOKRsp("保存成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RetResponse.makeErrRsp("保存失败");
        }
    }

    @Override
    public RetResult findAll(String name) {
        if (StringUtils.isNotBlank(name)) {
            FrmRole role = new FrmRole();
            role.setName(name);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
            Example<FrmRole> example = Example.of(role, matcher);
            return RetResponse.makeOKRsp(roleDao.findAll(example));
        } else {
            return RetResponse.makeOKRsp(roleDao.findAll());
        }
    }

    @Override
    public RetResult findByPermissionsCode(String code) {
        return RetResponse.makeOKRsp(roleDao.findByPermissionsRole_Code(code));
    }
}
